package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Merchant;
import com.sky.entity.User;
import com.sky.mapper.MerchantMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;



    // 用户登录
    @PostMapping("/login")
    public Result userLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录，接收到的参数是{}",userLoginDTO.getCode());
        // 获取用户信息
        User user = userService.userLogin(userLoginDTO);
        // 获取商家信息
        Merchant merchant = merchantMapper.selectById(1L);
        // 为微信用户生成jwt令牌
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        //计算配送费
        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, userLoginDTO.getLocation());

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .deliveryFee(delivoryCost)
                .build();

        return Result.success(userLoginVO);
    }

}
